package com.java.cg.seckill.service.impl;

import com.java.cg.seckill.entity.SeckillStatus;
import com.java.cg.seckill.task.MultiThreadingCreateOrder;
import com.java.common.constants.CacheKey;
import com.java.common.exception.RRException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.common.utils.PageUtils;
import com.java.common.utils.Query;

import com.java.cg.seckill.dao.SeckillOrderDao;
import com.java.cg.seckill.entity.SeckillOrder;
import com.java.cg.seckill.service.SeckillOrderService;

@Service("seckillOrderService")
public class SeckillOrderServiceImpl extends ServiceImpl<SeckillOrderDao, SeckillOrder> implements SeckillOrderService {
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private MultiThreadingCreateOrder multiThreadingCreateOrder;


	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		IPage<SeckillOrder> page = this.page(
				new Query<SeckillOrder>().getPage(params),
				new QueryWrapper<>()
		);

		return new PageUtils(page);
	}

	@Override
	public boolean add(Long id, String time, String username) {

		Long userQueueCount = redisTemplate.boundHashOps(CacheKey.SEC_KILL_QUEUE_REPEAT_KEY).increment(username, 1);
		//判断 是否大于1
		if (userQueueCount > 1) {
			throw new RRException("不允许重复购买!!");
		}


		/**
		 * 秒杀排队对象
		 * username 抢单的用户是谁
		 * status 1  表示抢单的状态 (1.排队中)
		 * id 抢的商品的ID
		 * time :抢的商品的所属时间段
		 */
		SeckillStatus seckillStatus = new SeckillStatus(username, new Date(), 1, id, time);

		//进入排队中
		redisTemplate.boundListOps(CacheKey.SEC_KILL_USER_QUEUE_KEY).leftPush(seckillStatus);

		//进入排队标识
		redisTemplate.boundHashOps(CacheKey.SEC_KILL_USER_STATUS_KEY).put(username, seckillStatus);

		//多线程下单
		multiThreadingCreateOrder.createrOrder();
		return true;
	}

	@Override
	public SeckillStatus queryStatus(String username) {
		return (SeckillStatus) redisTemplate.boundHashOps(CacheKey.SEC_KILL_USER_STATUS_KEY).get(username);
	}

}